import 'package:auto_size_text/auto_size_text.dart';
import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'PTDropDownMenuRoute.dart';

//下拉框
class PTDropDownMenu extends StatefulWidget {
  final Function(dynamic data) clickBack;
  final double fLeftPandingX;
  final double fHeight; //下拉框H
  final double fItemHeight; //每个Item H
  final List<String> mlist; //list
  final int iSelTag; //选中
  final double fFramHeight; //边框H
  final double fWidth; //按钮的宽度
  final String hintText;
  final bool bIsShowCloseBtn; //是否有X清除已选
  final bool bIsReSet;

  const PTDropDownMenu({
    Key? key,
    required this.clickBack,
    this.fLeftPandingX = 0,
    this.fHeight = 120,
    required this.mlist,
    this.iSelTag = 0,
    this.fItemHeight = 40,
    this.fFramHeight = 44,
    this.fWidth = 160,
    this.hintText = "请选择",
    this.bIsShowCloseBtn = false,
    this.bIsReSet = false,
  }) : super(key: key);

  @override
  // ignore: library_private_types_in_public_api
  PTDropDownMenuState createState() => PTDropDownMenuState();
}

class PTDropDownMenuState extends State<PTDropDownMenu> {
  final GlobalKey _globalKey = GlobalKey();
  late int _selectedItemIndex;
  bool _bIsPopRoute = false;

  @override
  void initState() {
    super.initState();
    _selectedItemIndex = widget.iSelTag;
  }

  @override
  void didUpdateWidget(PTDropDownMenu oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (!const DeepCollectionEquality().equals(widget.mlist, oldWidget.mlist)) {
      if (widget.mlist.isNotEmpty) {
        _selectedItemIndex =
            _selectedItemIndex.clamp(0, widget.mlist.length - 1);
      }
    }

    if (widget.iSelTag != oldWidget.iSelTag) {
      _selectedItemIndex = widget.iSelTag;
    }

    //重置
    if (widget.bIsReSet) {
      _selectedItemIndex = widget.iSelTag;
    }
  }

  void resetOptions() {
    _selectedItemIndex = 0;
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      heightFactor: 1.0,
      child: Container(
        key: _globalKey,
        height: widget.fFramHeight,
        width: widget.fWidth,
        decoration: BoxDecoration(
          borderRadius: const BorderRadius.all(Radius.circular(6)),
          border: Border.all(width: 0.5, color: Colors.grey),
        ),
        child: widget.mlist.isNotEmpty
            ? (!widget.bIsShowCloseBtn ? normalWidget() : cleanWidget())
            : Center(
                child: Text(
                  widget.hintText,
                  style: const TextStyle(
                    fontSize: 16,
                    color: Colors.grey,
                  ),
                ),
              ),
      ),
    );
  }

  //可清除已选
  Widget cleanWidget() {
    return Row(
      mainAxisSize: MainAxisSize.max,
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        const SizedBox(
          width: 10,
        ),
        Expanded(
            child: InkWell(
                splashColor: Colors.transparent,
                highlightColor: Colors.transparent,
                onTap: () {
                  onClick();
                },
                child: AutoSizeText(
                  _selectedItemIndex >= 0
                      ? widget.mlist[_selectedItemIndex]
                      : widget.hintText,
                  style: TextStyle(
                      fontSize: 16,
                      color:
                          (_selectedItemIndex >= 0 || widget.mlist.isNotEmpty)
                              ? Colors.black
                              : Colors.grey),
                ))),
        GestureDetector(
          onTap: () {
            if (_selectedItemIndex >= 0) {
              setState(() {
                _selectedItemIndex = -1;
                widget.clickBack(-1);
              });
            }
          },
          child: Icon(
              _bIsPopRoute
                  ? Icons.arrow_drop_up
                  : (_selectedItemIndex >= 0
                      ? Icons.close
                      : Icons.arrow_drop_down),
              size: 20,
              color: Colors.black),
        ),
        const SizedBox(
          width: 10,
        ),
      ],
    );
  }

  //正常
  Widget normalWidget() {
    return InkWell(
      splashColor: Colors.transparent,
      highlightColor: Colors.transparent,
      onTap: () {
        onClick();
      },
      child: Row(
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          const SizedBox(
            width: 8,
          ),
          Expanded(
              child: Text(
            _selectedItemIndex >= 0
                ? widget.mlist[_selectedItemIndex]
                : widget.hintText,
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
            textAlign: TextAlign.left,
            style: TextStyle(
                fontSize: 16,
                color: (_selectedItemIndex >= 0) //|| widget.mlist.isNotEmpty
                    ? Colors.black
                    : Colors.grey),
          )),
          Icon(_bIsPopRoute ? Icons.arrow_drop_up : Icons.arrow_drop_down,
              size: 20, color: Colors.black),
          const SizedBox(
            width: 8,
          ),
        ],
      ),
    );
  }

  void onClick() {
    setState(() {
      _bIsPopRoute = true;
    });

    RenderBox? renderBox =
        _globalKey.currentContext!.findRenderObject() as RenderBox?;
    Rect box = renderBox!.localToGlobal(Offset.zero) & renderBox.size;
    Navigator.push(
        context,
        DropDownMenuRoute(
          mlist: widget.mlist,
          position: box,
          menuHeight: widget.fHeight,
          fPosX: widget.fLeftPandingX != 0 ? widget.fLeftPandingX : box.left,
          itemHeight: widget.fItemHeight,
          iSelTag: _selectedItemIndex,
          clickBack: (dynamic data) {
            widget.clickBack(data);
            setState(() {
              _selectedItemIndex = data;
              _bIsPopRoute = false;
            });
          },
          popBack: () {
            setState(() {
              _bIsPopRoute = false;
            });
          },
        ));
  }
}
